package com.cndatacom.eweb.dao.impl;

import java.util.List;

import com.cndatacom.eweb.common.PaginationModel;
import com.cndatacom.eweb.common.PaginationSupport;
import com.cndatacom.eweb.dao.IOrganizationDao;
import com.cndatacom.eweb.model.Organization;
import com.cndatacom.eweb.model.UserOrganization;

public class OrganizationDao extends PaginationSupport implements IOrganizationDao {

	public Organization addOrUpdateOrganization(Organization organization) {
		getHibernateTemplate().saveOrUpdate(organization);
		return organization;

	}

	public boolean addOrUpdateUserOrganization(UserOrganization userOrganization) {
		getHibernateTemplate().saveOrUpdate(userOrganization);
		return true;
	}

	public boolean deleteOrganization(Organization organization) {
		getHibernateTemplate().delete(organization);
		return true;
	}

	public boolean deleteUserOrganization(UserOrganization userOrganization) {
		getHibernateTemplate().delete(userOrganization);
		return true;
	}

	public PaginationModel getAllOrganization(int offset, int pageSize, boolean paging) {
		return searchPaginated("select o from Organization o order by o.id desc", null, offset, pageSize, paging);
	}

	public PaginationModel getAllOrganizationUsers(int organizationId, int offset, int pageSize) {
		return searchPaginated("select uo from UserOrganization uo where uo.organization.id = ? order by uo.id desc", organizationId, offset, pageSize, true);
	}

	public Organization getOrganationById(int id) {
		return (Organization)getHibernateTemplate().get(Organization.class, id);
	}

	@SuppressWarnings("unchecked")
	public UserOrganization getUserOrganizationByUseridAndOrganizationid(int userId, int organizationId) {
		Object[] params = new Object[]{userId, organizationId};
		List userOrganizationList = getHibernateTemplate().find("select uo from UserOrganization uo where uo.user.id = ? and uo.organization.id = ? order by uo.id desc", params);
		if(userOrganizationList!=null && userOrganizationList.size()>=1){
			return (UserOrganization)userOrganizationList.get(0);
		}
		return null;
	}

	public PaginationModel getOrganizationByParentId(int parentId, int offset, int pageSize) {
		if(parentId == 0) {
			return searchPaginated("select o from Organization o where o.parent = null order by o.id desc", offset, pageSize);
		}
		return searchPaginated("select o from Organization o where o.parent.id = ? order by o.id desc", parentId, offset, pageSize,true);
	}

}

